<template>
  <div class="main">
    <!-- 乘机人 -->
    <div class="passenger">
      <h2>乘机人</h2>
      <el-form :model="{users}" ref="passengerForm">
        <div class="item" v-for="(item,index) in users" :key="index">
          <el-form-item
            label="乘机人"
            :rules="passengerRules.username"
            :prop="`users[${index}].username`"
          >
            <el-input v-model="item.username" placeholder="姓名"></el-input>
          </el-form-item>
          <el-form-item label="证件号码" :rules="passengerRules.id" :prop="`users[${index}].id`">
            <el-input placeholder="登机证件号码" v-model="item.id">
              <el-select v-model="type" slot="prepend" placeholder="请选择">
                <el-option label="身份证号码" value="1"></el-option>
                <el-option label="护照" value="2"></el-option>
              </el-select>
            </el-input>
          </el-form-item>
          <span @click="removeUser(index)">-</span>
        </div>
        <el-button type="primary" @click="addUser">添加乘机人</el-button>
      </el-form>
    </div>
    <!-- 保险 -->
    <div class="safety">
      <h2>保险</h2>
      <el-checkbox-group v-model="checkList">
        <el-checkbox
          :label="item.id"
          v-for="item in data.insurances"
          :key="item.id"
          border
        >{{item.type}}：￥{{item.price}}/份×1 最高赔付{{item.compensation}}</el-checkbox>
      </el-checkbox-group>
    </div>
    <!-- 联系人 -->
    <div class="contact">
      <h2>联系人</h2>
      <el-form ref="contactForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="姓名" prop="contactName">
          <el-input v-model="form.contactName"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="contactPhone">
          <el-input v-model="form.contactPhone">
            <template slot="append">
              <el-button
                @click="getCaptchas"
                :disabled="postCode.noCode"
              >{{postCode.noCode?postCode.text:'发送验证码'}}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-input v-model="form.captcha"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <el-button type="warning" class="submitBtn" @click="submitData">提交订单</el-button>
  </div>
</template>

<script>
export default {
  props: ["data"],
  data() {
    return {
      type: "1", //证件类型
      //乘机人
      users: [
        {
          username: "",
          id: ""
        }
      ],
      //   保险
      checkList: [],
      //联系人信息
      form: {
        contactName: "",
        captcha: "",
        contactPhone: ""
      },
      //验证码信息
      postCode: {
        isCode: "", //验证码
        noCode: false, //禁止发送
        text: "" //验证码倒计时文字
      },
      //联系人信息验证
      rules: {
        contactPhone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: "手机号码格式错误",
            trigger: "blur"
          }
        ],
        captcha: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value != this.postCode.isCode) {
                callback(new Error("验证码错误"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        contactName: [
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ]
      },
      //乘机人验证
      passengerRules: {
        username: [
          { required: true, message: "乘机人不能为空", trigger: "blur" }
        ],
        id: [
          { required: true, message: "请输入证件号码", trigger: "blur" },
          {
            //注意：在自定义规则中要保证每个分支都有可执行的callback回调函数
            //否则在最终表单验证（validate）会进不去回调函数
            validator: (rule, value, callback) => {
              if (this.type == 1) {
                var reg = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
                if (!reg.test(value)) {
                  callback(new Error("身份证格式错误"));
                }
                callback();
              } else if (this.type == 2) {
                var reg = /^([a-zA-z]|[0-9]){5,17}$/;
                if (!reg.test(value)) {
                  callback(new Error("护照格式错误"));
                }
                callback();
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      }
    };
  },
  watch: {
    users: {
      handler() {
        this.totalPrice();
      },
      immediate: true
    },
    checkList: {
      handler() {
        this.totalPrice();
      },
      immediate: true
    }
  },
  methods: {
    //添加乘机人
    addUser() {
      this.users.push({
        username: "",
        id: ""
      });
    },
    //删除乘机人
    removeUser(index) {
      this.users.splice(index, 1);
    },
    //获取验证码
    getCaptchas() {
      var reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
      if (reg.test(this.form.contactPhone)) {
        this.$axios({
          url: "/captchas",
          method: "post",
          data: {
            tel: this.form.contactPhone
          }
        }).then(res => {
          this.postCode.isCode = res.data.code;
          this.$message({
            message: "验证码：" + this.postCode.isCode,
            type: "success",
            duration: 5000
          });
          this.Countdown();
        });
      } else {
        this.$message.error("请输入正确的手机号");
      }
    },
    //验证码倒计时完成后获取
    Countdown() {
      var time = 60;
      var timeID = setInterval(() => {
        time--;
        if (time > 0) {
          this.postCode.text = `${time}秒后可重发`;
          this.postCode.noCode = true;
        } else {
          time = 60;
          this.postCode.text = "发送验证码";
          this.postCode.noCode = false;
          clearInterval(timeID);
        }
      }, 1000);
    },
    //计算总价
    totalPrice() {
      var res = 0;
      res += this.data.seat_infos.par_price * this.users.length;
      this.data.insurances.forEach(item => {
        if (this.checkList.indexOf(item.id) >= 0) {
          res += item.price * this.users.length;
        }
      });
      res += this.data.airport_tax_audlet * this.users.length;
      this.$emit("setTotalPrice", res);
    },
    //提交数据
    async submitData() {
      var passengerValid = await this.$refs.passengerForm
        .validate()
        .catch(e => {});
      var contactValid = await this.$refs.contactForm.validate().catch(e => {});
      if (passengerValid && contactValid) {
        var data = {
          users: this.users,
          insurances: this.checkList,
          ...this.form,
          air: this.$route.query.id,
          seat_xid: this.$route.query.seat_xid,
          invoice: false
        };
        this.$axios({
          url: "/airorders",
          method: "post",
          headers: {
            Authorization: "Bearer " + this.$store.state.user.userInfo.token
          },
          data
        })
          .then(res => {
            if (res.data.message == "订单提交成功") {
              this.$message.success("订单提交成功");
              this.$router.push("/air/pay?id=" + res.data.data.id);
            }
          })
          .catch(err => {
            console.log("请求失败");
          });
      }
    }
  }
};
</script>

<style lang="less" scoped>
.main {
  flex: 1;
  margin-right: 50px;
  /deep/ .el-select .el-input {
    width: 130px;
  }
  > div {
    border-bottom: 1px dashed #ddd;
    padding-bottom: 20px;
    margin-bottom: 20px;
    &:nth-child(3) {
      border-bottom: none;
    }
  }
  h2 {
    font-size: 22px;
    margin-bottom: 20px;
    font-weight: 400;
  }
  .passenger {
    .el-button {
      margin-top: 20px;
    }
    .item {
      position: relative;
      border-bottom: 1px dashed #ddd;
      padding-bottom: 20px;
      &:nth-child(1) {
        span {
          display: none;
        }
      }
      span {
        position: absolute;
        top: 100px;
        right: -20px;
        height: 15px;
        width: 15px;
        background: #ddd;
        border-radius: 50%;
        color: #fff;
        line-height: 15px;
        text-align: center;
        cursor: pointer;
      }
    }
  }
  .safety {
    .el-checkbox-group {
      .el-checkbox {
        margin-left: 0;
        margin-bottom: 10px;
      }
    }
  }
  .contact {
    .el-input {
      width: 50%;
    }
  }
  .submitBtn {
    display: block;
    margin: 20px auto;
    width: 250px;
    height: 50px;
  }
}
</style>